package com.itstyle.seckill.common.utils;

import java.util.ArrayList;
import java.util.List;

public class MyContainerVolatile {
    volatile  List list = new ArrayList();
    public void add(Object o) {  //add
        list.add(o);
    }
    public int size() {   //size
        return list.size();
    }

    public static void main(String[] args) {
        MyContainerVolatile mcv = new MyContainerVolatile();
        new Thread( () -> {  //该线程负责往list里添加
            for (int i=0; i<10; i++) {
                mcv.add(new Object());
                System.out.print(" add-" + i);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();
        new Thread( () -> { //该线程一直监测list的size，直到size=5
            while(true) {  //一直监测着，很浪费CPU
                if(mcv.size() == 5) {  //此处未加同步，仍然可能会出现t1中又一次++为6了，才break
                    break;
                }
            }
            System.out.print(" t2结束 ");
        },"t2").start();
    }
}